#include "chmotor_modbus_rtu.h"
#include <stdio.h>
#include <ctype.h>

#pragma pack(1)


#pragma pack()

static int16_t int16_ltoh(int16_t data) {
  return (int16_t)((data & 0xff) << 8 | data >> 8);
}

static uint16_t uint16_ltoh(uint16_t data) {
  return (uint16_t)((data & 0xff) << 8 | data >> 8);
}

// 小写字母换成大写字母
void to_uppercase(char *str) {
  while (*str) {
    *str = toupper((unsigned char)*str);
    str++;
  }
}

void to_lowercase(char *str) {
  while (*str) {
    *str = tolower((unsigned char)*str);
    str++;
  }
}

/*
int tolower(int c)
{
	if ((c >= 'A') && (c <= 'Z'))
		return c + ('a' - 'A');
	return c;
}

int toupper(int c)
{
	if ((c >= 'a') && (c <= 'z'))
		return c + ('A' - 'a');
	return c;
}
*/

int main(int argc, char const *argv[]) {
  /* code */
  printf("read register\n");
  if (chmotor_modbus_read_register(CHMOTOR_DEV_SALVE_ADDR_M1, CHMOTOR_REG_ADDR_BUSBARVOL_R, 0x01)) {
    printf("pack len: %d\n", chmotor_modbus_pack_get_packlen());
    for (int i = 0; i < chmotor_modbus_pack_get_packlen(); i++) {
      printf("%02x ", chmotor_modbus_pack_get_packbuff()[i]);
    }
  }
  printf("\n");

  // ----------------------------------------------
  int16_t speed_set = 1200;
  speed_set = int16_ltoh(speed_set);

  printf("write register\n");
  if (chmotor_modbus_write_register(CHMOTOR_DEV_SALVE_ADDR_M1, CHMOTOR_REG_ADDR_SPEED_W, (uint8_t*)&speed_set, sizeof(speed_set))) {
    printf("pack len: %d\n", chmotor_modbus_pack_get_packlen());
    for (int i = 0; i < chmotor_modbus_pack_get_packlen(); i++) {
      printf("%02x ", chmotor_modbus_pack_get_packbuff()[i]);
    }
  }
  printf("\n");

  char str[] = "hello world";
  to_uppercase(str);
  printf("Uppercase: %s\n", str);
  to_lowercase(str);
  printf("Lowercase: %s\n", str);

  return 0;
}
